package org.example.controller;

import org.example.entity.ApiHistory;
import org.example.entity.CommonResult;
import org.example.service.ApiService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
public class ApiController {

	@Resource
	private ApiService apiService;


	//远程api调用
	@PostMapping("/api/{apiKey}")
	public CommonResult<Void> api(@PathVariable("apiKey") String apiKey, @RequestPart("file") MultipartFile file) {
		return this.apiService.api(apiKey, file);
	}

	@GetMapping("/file/{fileId}")
	public void downloadFile(@PathVariable("fileId") String fileId, HttpServletResponse httpServletResponse) {
		try {
			this.apiService.downloadFile(fileId, httpServletResponse);
		} catch (IOException e) {
			try {
				httpServletResponse.sendError(404, "下载失败");
			} catch (IOException ex) {
				throw new RuntimeException(ex);
			}
		}
	}


	@GetMapping("/api/key")
	public CommonResult<String> getKey() {
		return this.apiService.getKey();
	}


	@PutMapping("/api/key")
	public CommonResult<String> updateKey() {
		return this.apiService.updateKey();
	}

	@GetMapping("/api/history")
	public CommonResult<List<ApiHistory>> getHistory() {
		return this.apiService.getHistory();
	}
}
